package com.em.tuppence.web.controllers.registration;

import javax.servlet.http.HttpSession;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.em.tuppence.core.model.application.User;
import com.em.tuppence.core.model.exceptions.TuppenceUserAlreadyExistsException;
import com.em.tuppence.web.security.details.TuppenceUserDetails;
import com.em.tuppence.web.services.client.UserServiceProxy;

@Controller
@RequestMapping(value = "/registration/register.html")
@SessionAttributes(types = User.class, value={"open-id-user-object"})
public class RegistrationController {

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
    		//you can't edit these field
    		dataBinder.setDisallowedFields("secret");
    		dataBinder.setDisallowedFields("id");
            dataBinder.setDisallowedFields("openIdUrl");
    }
	
	@RequestMapping(method = RequestMethod.GET)
	public String startRegistration(Model model, HttpSession session) {
		User user = (User)session.getAttribute("open-id-user-object");
		
		//force logout if the user is null or the openid url is missing
		if(user == null || user.getOpenIdUrl() == null || user.getOpenIdUrl().isEmpty()) {
			return "redirect:logout";
		}
		
		//add the model to the... um... spring model
		model.addAttribute(user);
		
		//go to the registration page
		return "registration/register";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String registerUser(@ModelAttribute User user, BindingResult result, SessionStatus status) {
		
		UserServiceProxy proxy = new UserServiceProxy();
		try {
			proxy.addUser(user);
		} catch (TuppenceUserAlreadyExistsException e) {
			e.printStackTrace();
			return "registration/register";
		}
		//destroy proxy
		proxy.destroy();
		
		if(result.hasErrors()) {
			return "registration/register";
		}
		
		//create new user details for you to be registered under
		TuppenceUserDetails details = new TuppenceUserDetails(user);
		
		//update credentials with (newly) registered user
		SecurityContextHolder.getContext().setAuthentication(
			new OpenIDAuthenticationToken(details, details.getAuthorities(), user.getOpenIdUrl(), null)
		);
		
		return "app/home";
	}
	
}
